<?php
require_once __DIR__ . '/../aliyun-oss-php-sdk/autoload.php';
require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/../php_config/AliyunConfig.php';



use OSS\OssClient;
use OSS\Core\OssException;


use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;

class Aliyun
{
    const endpoint = 'http://oss-cn-shanghai.aliyuncs.com';
    const bucket = 'huiguo-oov';
    const ImageSegHost = 'imageseg.cn-shanghai.aliyuncs.com';

    private $bucket, $endpoint;

    public function __construct($bucket = null, $endpoint = null)
    {
        $this->bucket = $bucket ?? self::bucket;
        $this->endpoint = $endpoint ?? self::endpoint;
    }

    /**
     * @param string[] $args
     * @return void
     */
    public static function segImage($url)
    {
        AlibabaCloud::accessKeyClient(AliyunConfig::ACCESS_KEY_ID, AliyunConfig::ACCESS_KEY_SECRET)
            ->regionId('cn-shanghai')
            ->asDefaultClient();

        try {
            $result = AlibabaCloud::imageseg()
                ->v20191230()
                ->segmentCommodity()
                ->options(['query' => [
                    'ImageURL' => $url
                ]])
                ->request();
            return $result->toArray();
        } catch (ClientException $e) {
            print_r($e->getErrorMessage());
        } catch (ServerException $e) {
            print_r($e->getErrorMessage());
        }
        return null;
    }

    public function putOSSObject($objectName, $filePath)
    {
        try {
            $ossClient = new OssClient(AliyunConfig::ACCESS_KEY_ID, AliyunConfig::ACCESS_KEY_SECRET, $this->endpoint);
            return [true, $ossClient->uploadFile($this->bucket, $objectName, $filePath)];
        } catch (OssException $e) {
            return [false, $e->getMessage()];
        }
        return [false, '未知'];
    }
}
